package com.one.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.one.common.core.constants.Constants;
import com.one.common.core.domain.QueryDataDTO;
import com.one.common.core.domain.TableDataInfo;
import com.one.common.core.enums.ExamListType;
import com.one.common.core.util.ThreadLocalUtil;
import com.one.friend.domain.exam.vo.ExamVO;
import com.one.friend.domain.message.dto.MessageDTO;
import com.one.friend.domain.message.vo.MessageTextVO;
import com.one.friend.manager.MessageCacheManager;
import com.one.friend.mapper.message.MessageMapper;
import com.one.friend.service.user.IUserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserMessageServiceImpl implements IUserMessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageCacheManager messageCacheManager;

    @Override
    public TableDataInfo list(QueryDataDTO queryDataDTO) {
        //先查询缓存（u:e:l:用户id）  如果缓存能够查询到
        //如果查询不到   数据库当中再去查询  并且将数据库中的数据同步给redis
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if (total == null || total <= 0) {
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(queryDataDTO.getPageNum(), queryDataDTO.getPageSize());
            messageTextVOList = messageMapper.selectUserMessageList(userId);
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        } else {
            messageTextVOList = messageCacheManager.getMessageVOList(queryDataDTO,userId);
            total = messageCacheManager.getListSize(userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(messageTextVOList, total);
    }
}
